<template>
  <div class="cart-container">
    <el-card class="cart-card">
      <template #header>
        <div class="cart-header">
          <h2>我的购物车</h2>
          <el-button 
            type="danger" 
            :disabled="selectedItems.length === 0"
            @click="clearCart"
          >
            清空购物车
          </el-button>
        </div>
      </template>

      <el-table
        :data="cartItems"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="资料" width="300">
          <template #default="{row}">
            <div class="material-info">
              <h4>{{ row.material.title }}</h4>
              <p class="file-type">{{ row.material.fileType.toUpperCase() }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="水印" width="120">
          <template #default="{row}">
            <el-tag :type="row.isWatermark ? '' : 'success'">
              {{ row.isWatermark ? '带水印' : '无水印' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="价格" width="120">
          <template #default="{row}">
            {{ row.isWatermark 
              ? row.material.price 
              : row.material.price + row.material.noWatermarkPrice }} 虚拟币
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button 
              type="danger" 
              size="small"
              @click="removeItem(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-footer">
        <div class="total">
          <p>已选择 {{ selectedItems.length }} 个商品</p>
          <p class="total-price">总计: {{ totalCost }} 虚拟币</p>
        </div>
        <el-button-group>
          <el-button 
            type="primary" 
            size="large"
            :disabled="selectedItems.length === 0"
            @click="checkout"
          >
            结算 ({{ selectedItems.length }})
          </el-button>
          <el-button 
            type="primary" 
            size="large"
            :disabled="selectedItems.length === 0"
            @click="batchDownload"
          >
            打包下载
          </el-button>
        </el-button-group>
      </div>
    </el-card>
    
    <DownloadProgress 
      v-if="showProgress"
      :task-id="taskId"
      :visible="showProgress"
      :title="'资料打包下载'"
      @update:visible="showProgress = $event"
      @retry="batchDownload"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { getCartItems, removeFromCart, clearCartItems, checkoutCart } from '@/api/cart'
import DownloadProgress from '@/components/DownloadProgress.vue'
import { batchDownload as apiBatchDownload } from '@/api/download'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const cartItems = ref([])
const selectedItems = ref([])

// 加载购物车
const loadCart = async () => {
  try {
    const res = await getCartItems()
    cartItems.value = res.data
  } catch (error) {
    console.error('加载购物车失败:', error)
  }
}

// 移除商品
const removeItem = async (id) => {
  try {
    await removeFromCart(id)
    await loadCart()
  } catch (error) {
    console.error('移除商品失败:', error)
  }
}

// 清空购物车
const clearCart = async () => {
  try {
    await clearCartItems()
    await loadCart()
    selectedItems.value = []
  } catch (error) {
    console.error('清空购物车失败:', error)
  }
}

const router = useRouter()

// 结算
const checkout = async () => {
  try {
    const res = await checkoutCart({
      cartItemIds: selectedItems.value.map(item => item.id)
    })
    
    if (res.data.success) {
      // 跳转到结算结果页
      router.push({
        path: '/payment/checkout-result',
        query: {
          data: encodeURIComponent(JSON.stringify(res.data.data))
        }
      })
    } else {
      if (res.data.message === '虚拟币余额不足') {
        ElMessage.warning({
          message: `虚拟币不足，当前余额${res.data.available}，还需${res.data.required - res.data.available}`,
          duration: 3000,
          showClose: true
        })
      } else {
        ElMessage.error(res.data.message || '结算失败')
      }
    }
  } catch (error) {
    console.error('结算失败:', error)
    ElMessage.error('结算失败')
  }
}

// 计算总价
const totalCost = computed(() => {
  return selectedItems.value.reduce((sum, item) => {
    return sum + (item.isWatermark 
      ? item.material.price 
      : item.material.price + item.material.noWatermarkPrice)
  }, 0)
})

// 选择变化
const handleSelectionChange = (selection) => {
  selectedItems.value = selection
}

// 清理已下载的购物车项
const clearDownloadedItems = async (materialIds) => {
  try {
    await Promise.all(materialIds.map(id => {
      return removeFromCart(id)
    }))
    await loadCart()
  } catch (error) {
    console.error('清理购物车失败:', error)
    ElMessage.warning('部分商品可能未能成功从购物车中移除')
  }
}

// 打包下载
const showProgress = ref(false)
const taskId = ref('')

const batchDownload = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择要下载的商品')
    return
  }

  try {
    const materialIds = selectedItems.value.map(item => item.material.id)
    const res = await apiBatchDownload(materialIds)
    
    if (!res.headers['x-task-id']) {
      throw new Error('未获取到任务ID')
    }
    
    taskId.value = res.headers['x-task-id']
    
    if (res.data.success) {
      // 显示进度对话框
      showProgress.value = true
      
      // 创建隐藏iframe触发下载
      const iframe = document.createElement('iframe')
      iframe.src = res.data.downloadUrl
      iframe.style.display = 'none'
      document.body.appendChild(iframe)
      
      // 清理下载完成的商品
      setTimeout(() => {
        iframe.remove()
        clearDownloadedItems(materialIds)
      }, 1000)
    } else {
      throw new Error(res.data.message || '打包下载失败')
    }
  } catch (error) {
    console.error('打包下载失败:', error)
    ElMessage.error(error.message || '打包下载失败，请稍后重试')
  }
}

onMounted(() => {
  loadCart()
})
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.material-info h4 {
  margin: 0;
  font-size: 16px;
}

.material-info .file-type {
  margin: 5px 0 0;
  color: #909399;
  font-size: 12px;
}

.cart-footer {
  margin-top: 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total {
  text-align: right;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: var(--el-color-primary);
  margin-top: 5px;
}
</style>